import React, { Component } from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import styles from './index.module.scss'
import logo from 'assets/logo.png'
import { login } from 'api/user'
import { setToken } from 'utils/storage'

export default class index extends Component {
	onFinish = async (value) => {
		try {
			// 发送请求登录
			const res = await login(value)
			message.success('登录成功！')
			// 保存到本地
			setToken(res.data)
			// 跳转
			const { state } = this.props.location
				this.props.history.push(state?.fromPath ?? '/home')
		} catch (error) {
			message.error('登陆错误！')
			console.log(error)
		}
	}

	render() {
		return (
			<div className={styles.login}>
				<Card className="login-container">
					<img src={logo} className="logo" alt="" />

					<Form
						onFinish={this.onFinish}
						name="basic"
						size="large"
						validateTrigger={['onBlur', 'onChange']}
						initialValues={{
							mobile: '13800000000',
							code: '246810',
							agree: false,
						}}
					>
						<Form.Item
							name="mobile"
							rules={[
								{
									required: true,
									message: '请输入手机号！',
								},
								{
									pattern:
										/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
									message: '手机格式不正确!',
								},
							]}
						>
							<Input />
						</Form.Item>

						<Form.Item
							name="code"
							rules={[
								{
									required: true,
									message: '请输入验证码！',
								},
								{
									pattern: /^[0-9]{6}$/,
									message: '验证码格式不正确!',
								},
							]}
						>
							<Input.Password />
						</Form.Item>

						<Form.Item
							name="agree"
							valuePropName="checked"
							rules={[
								{
									validator(rule, value) {
										console.log(value)
										if (value) return Promise.resolve()
										return Promise.reject(
											new Error('未勾选！')
										)
									},
									message: '请勾选！',
								},
							]}
						>
							<Checkbox>
								我已阅读并同意「用户协议」和「隐私条款」
							</Checkbox>
						</Form.Item>

						<Form.Item>
							<Button block type="primary" htmlType="submit">
								Submit
							</Button>
						</Form.Item>
					</Form>
				</Card>
			</div>
		)
	}
}
